package com.demo.springBoot2.error;

import com.demo.springBoot2.result.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.stream.Collectors;

/**
 * @Author 750909637@qq.com
 * @PackageName demo
 * @Package com.edu.demo.demos.error
 * @Date 2024/3/6 19:58
 * @Version 1.0
 */
@RestController
@ControllerAdvice
public class ParameterError {
    //捕获空指针异常
//    @ExceptionHandler(NullPointerException.class)
//    public String nullPointerException() {
//        return "空指针异常";
//    }
    // 参数异常
    @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public ResponseEntity<Result<String>> handleValidatedException(Exception e) {
        Result<String>  result = null;
        if (e instanceof  MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex =(MethodArgumentNotValidException)  e;
            result = Result.error(86202,"参数校验异常",
                    ex.getBindingResult().getAllErrors().stream()
                            .map(ObjectError::getDefaultMessage)
                            .collect(Collectors.toList())
            );
        } else  if (e instanceof ConstraintViolationException){
            ConstraintViolationException ex = (ConstraintViolationException) e;
            result = Result.error(86202,"参数校验异常",
                    ex.getConstraintViolations().stream()
                            .map(ConstraintViolation::getMessage)
                            .collect(Collectors.toList())
            );
        }else  if (e instanceof BindException) {
            BindException  ex = (BindException ) e;
            result = Result.error(86202,"参数校验异常",
                    ex.getAllErrors().stream()
                            .map(ObjectError::getDefaultMessage)
                            .collect(Collectors.toList())
            );
        }
        return new ResponseEntity<>(result,HttpStatus.BAD_REQUEST);
    }
}
